package com.api.aiyh_pcn.fadada.util;

import aiyh.utils.Util;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils;
import aiyh.utils.zwl.common.ToolUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.h2.util.StringUtils;
import weaver.aiyh_pcn.fadada.entity.FileInfo;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/10/13 0013 11:46
 * 法大大请求方法
 */


public class FaDDRequestUtils {
	private final static HttpUtils httpUtils = new HttpUtils();
	private final static Map<String, String> header = httpUtils.getGlobalCache().header;
	private final static FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping();
	private final static ToolUtil TOOL_UTIL = new ToolUtil();

	static {
		String appId = TOOL_UTIL.getSystemParamValue("FDD_appId");
		if (StringUtils.isNullOrEmpty(appId)) {
			appId = "100001";
			TOOL_UTIL.writeErrorLog("查询到的FDD_appId为空！");
		}
		header.put("appId", appId);
		header.put("signType", "SHA256");
		String apiKey = TOOL_UTIL.getSystemParamValue("FDD_apiKey");
		if (StringUtils.isNullOrEmpty(apiKey)) {
			apiKey = "TulQxnZSRKeHoQfmeZzOUzGn6KpTDkDK";
			TOOL_UTIL.writeErrorLog("查询到的FDD_apiKey为空！");
		}
		header.put("apikey", apiKey);
		header.put("Content-Type", HttpArgsType.APPLICATION_JSON);
		TOOL_UTIL.writeErrorLog(JSONObject.toJSONString(header));
	}

	//	查询企业认证状态
	public static Map<String, Object> checkCompanyInfo(Map<String, Object> data) {
		header.put("sign", builderSign(data));
		try {
			ResponeVo responeVo = httpUtils.apiPost("http://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/account/company/info",
					data, null);
			TOOL_UTIL.writeDebuggerLog("查询企业认真状态：" + JSONObject.toJSONString(data));
			TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
//			System.out.println(responeVo.getEntityString());
			if (responeVo.getCode() != 200) {
				return null;
			}
			return responeVo.getEntityMap();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}


	//	创建合同
	public static ResponeVo createContract(FileInfo fileInfo, String url) {
		Map<String, Object> data = new HashMap<>();
		data.put("contractExtension", fileInfo.getContractExtension());
		data.put("contractTitle", fileInfo.getContractTitle());
		data.put("uploadType", fileInfo.getUploadType());
		data.put("customerNo", fileInfo.getCustomerNo());
		header.put("sign", builderSign(data));
		header.put("Content-Type", "multipart/form-data");
//		System.out.println(JSONObject.toJSONString(data));
		ResponeVo responeVo = null;
		try {
			responeVo = httpUtils.apiUploadFile(url,
					fileInfo.getFile(), "file", fileInfo.getImagefilename(), data, null);
			TOOL_UTIL.writeDebuggerLog("创建合同：" + JSONObject.toJSONString(data));
			TOOL_UTIL.writeDebuggerLog("返回信息：" + responeVo.getEntityString() + "\t 状态码：" + responeVo.getCode());
		} catch (IOException e) {
			e.printStackTrace();
			TOOL_UTIL.writeErrorLog(e.toString());
		}
//		System.out.println(JSONObject.toJSONString(responeVo));
		return responeVo;
	}


	//	签署合同
	public static ResponeVo signedContract(Map<String, Object> data, String url) {
		header.put("sign", builderSign(data));
		header.put("Content-Type", "application/json");
//		System.out.println(JSONObject.toJSONString(data));
		ResponeVo responeVo = null;
		try {
//			http://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign
			responeVo = httpUtils.apiPost(url,
					data, null);
			TOOL_UTIL.writeDebuggerLog("签署合同：" + JSONObject.toJSONString(data));
			TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
//			System.out.println(JSONObject.toJSONString(responeVo));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responeVo;
	}

	public static void downContract(Map<String, Object> data, Consumer<CloseableHttpResponse> consumer, String url) {
		header.put("sign", builderSign(data));
		header.put("Content-Type", "application/json");
		System.out.println(JSONObject.toJSONString(data));
		try {
			httpUtils.apiPost(url,
					data, null, consumer);
			TOOL_UTIL.writeDebuggerLog("下载合同文件：" + JSONObject.toJSONString(data));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Map<String, Object> queryContractStatus(Map<String, Object> data) throws JsonProcessingException {
		header.put("sign", builderSign(data));
		ResponeVo responeVo = null;
		try {
			responeVo = httpUtils.apiPost("https://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign/status/view",
					data, null);
			TOOL_UTIL.writeDebuggerLog("查询合同状态：" + JSONObject.toJSONString(data));
			TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
//		System.out.println(JSONObject.toJSONString(responeVo));
		return responeVo.getEntityMap();
	}

	public static Map<String, Object> queryDetailContractStatus(Map<String, Object> data) throws JsonProcessingException {
		header.put("sign", builderSign(data));
		ResponeVo responeVo = null;
		try {
			responeVo = httpUtils.apiPost("https://apigwaws.porsche-cloudservice.com/env-101/por-econtract/econtract/contract/api/v1/contract/sign/detail/view",
					data, null);
			TOOL_UTIL.writeDebuggerLog("查询合同状态：" + JSONObject.toJSONString(data));
			TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
//		System.out.println(JSONObject.toJSONString(responeVo));
		return responeVo.getEntityMap();
	}


	private static String builderSign(Map<String, Object> data) {
		header.put("timestamp", Util.getTime("yyyy-MM-dd HH:mm:ss"));
		header.put("bizContent", builderBizContent(data));
		String signStr = "appId=" + header.get("appId") +
				"&bizContent=" + header.get("bizContent") +
				"&signType=" + header.get("signType") +
				"&timestamp=" + header.get("timestamp");
//		System.out.println(signStr);
		String appKey = TOOL_UTIL.getSystemParamValue("FDD_appKey");
		if (StringUtils.isNullOrEmpty(appKey)) {
			TOOL_UTIL.writeErrorLog("查询到的FDD_appKey为空！");
			appKey = "L7P59oqA2An0XgJ1LeMN0fRu1";
		}
		TOOL_UTIL.writeDebuggerLog("app签名：" + appKey);
		TOOL_UTIL.writeDebuggerLog("signStr：" + signStr);
		TOOL_UTIL.writeDebuggerLog("请求头信息：" + JSONObject.toJSONString(header));
//		String appKey = "L7P59oqA2An0XgJ1LeMN0fRu1";
		String sha256 = string2SHA256(signStr) + appKey;
//		System.out.println(sign);
		return Base64.getEncoder().encodeToString(string2SHA256(sha256).getBytes(StandardCharsets.UTF_8));
	}

	public static String builderBizContent(Map<String, Object> data) {
		String jsonString = JSONUtil.toJsonStr(data);
		TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码：" + jsonString);
		String encode;
		//			encode = URLEncoder.encode(jsonString, "UTF-8");
		encode = URLUtil.encodeAll(jsonString, StandardCharsets.UTF_8);
		TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码后URLEncoder编码：" + encode);
		String s = Base64.getEncoder().encodeToString(encode.getBytes(StandardCharsets.UTF_8));
		TOOL_UTIL.writeDebuggerLog("bizContent进行JSON编码后URLEncoder编码后进行base64编码：" + s);
		return s;
	}

	private static String string2SHA256(String str) {
		MessageDigest messageDigest;
		String encdeStr = "";
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			byte[] hash = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8));
			encdeStr = Hex.encodeHexString(hash);
			TOOL_UTIL.writeDebuggerLog("进行SHA-256加密：" + encdeStr);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		String s = encdeStr.toUpperCase();
		TOOL_UTIL.writeDebuggerLog("进行SHA-256加密后转为全大写：" + s);
		return s;
	}

}

